import React, { Component } from "react";
import { connect } from "dva";
import vd from "validator";
import {
  Form,
  Input,
  Row,
  Col,
  Button,
  Steps,
  Icon,
  Table,
  Modal,
  Notification,
  Breadcrumb
} from "antd";
import { Link } from "dva/router";
import { gup } from "../../utils/utils";
import PMap from "../../components/Pro/PMap";

import {
  taskAttendanceComAttendGroupInSecondStepAttendGroup, //进入考勤组设置-第二步页面
  taskAttendanceComAttendGroupSaveSecondStepAttendGroup //新增或者修改考勤组-第二步-设置考勤地址
} from "../../services/api";

import "./ThiftManagement.less";

const FormItem = Form.Item;
const { Step } = Steps;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 7 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 10 }
  }
};

const submitFormLayout = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 10, offset: 7 }
  }
};

@connect(state => ({
  profile: state.profile
}))
@Form.create()
export default class Information extends Component {
  state = {
    point: [],
    address: "",
    visible: false, //添加地点
    attendGroupId: gup("attendGroupId") || "",
    midAttendGroupId: gup("midAttendGroupId") + "" || "",
    addressRange: "100",
    comAttendAddressJson: [],
    pagenav: {
      current: 1,
      pageSize: 10,
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: total => `总共 ${total} 条`,
      onShowSizeChange: (current, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = current;
        pagenav.pageSize = pageSize;
        this.setState({ pagenav });
        setTimeout(() => {
          this.bbdExampersonPage();
        });
      },
      onChange: (page, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = page;
        pagenav.pageSize = pageSize;
        this.setState({ pagenav });
        setTimeout(() => {
          this.bbdExampersonPage();
        });
      },
      total: 0
    }
  };

  componentDidMount() {
    this.taskAttendanceComAttendGroupInSecondStepAttendGroup();
  }

  taskAttendanceComAttendGroupSaveSecondStepAttendGroup = () => {
    const {
      midAttendGroupId,
      comAttendAddressJson,
      addressRange,
      attendGroupId
    } = this.state;
    taskAttendanceComAttendGroupSaveSecondStepAttendGroup({
      midAttendGroupId,
      attendGroupId,
      comAttendAddressJson: JSON.stringify(comAttendAddressJson),
      addressRange
    })
      .then(res => {
        console.log(res, "新增或者修改考勤组-第二步-设置考勤地址-res");
        this.props.history.push(
          `/attendancemanagement/settingupattendance?attendGroupId=${
            res.data.attendGroupId
          }&midAttendGroupId=${res.data.midAttendGroupId}`
        );
      })
      .catch(err =>
        console.log(err, "新增或者修改考勤组-第二步-设置考勤地址-err")
      );
  };

  taskAttendanceComAttendGroupInSecondStepAttendGroup = () => {
    taskAttendanceComAttendGroupInSecondStepAttendGroup({
      midAttendGroupId: this.state.midAttendGroupId,
      attendGroupId: this.state.attendGroupId
    })
      .then(res => {
        console.log(res, "进入考勤组设置-第二步页面-res");
        if (res.data) {
          const { addressRange, attendGroupId, midAttendGroupId } = res.data;
          let comAttendAddressJson = JSON.parse(res.data.comAttendAddressJson);
          comAttendAddressJson = comAttendAddressJson.map((val, i) => {
            const obj = { ...val };
            obj.key = i;
            return obj;
          });
          this.setState({
            attendGroupId,
            midAttendGroupId,
            addressRange: addressRange || 100,
            comAttendAddressJson
          });
        }
      })
      .catch(err => console.log(err, "进入考勤组设置-第二步页面-err"));
  };
  /* 考勤地点--drawer */
  columns = [
    {
      key: "1",
      title: "考勤地点",
      dataIndex: "address",
      render: text => <span>{text}</span>
    },
    {
      width: 60,
      title: "操作",
      dataIndex: "b",
      render: (rext, record) => (
        <span
          onClick={() => {
            const { comAttendAddressJson } = this.state;
            const newarr = comAttendAddressJson.map(val => {
              return val;
            });
            newarr.splice(record.key, 1);
            console.log(record.key, newarr);
            this.setState({ comAttendAddressJson: newarr });
          }}
          style={{ color: "#0F71FF" }}
        >
          删除
        </span>
      )
    }
  ];

  handleSubmit = e => {
    e.preventDefault();
    if (this.state.comAttendAddressJson.length === 0) {
      Notification.error({
        message: "请选择考勤地点"
      });
      return;
    }
    this.props.form.validateFieldsAndScroll(err => {
      if (!err) {
        this.taskAttendanceComAttendGroupSaveSecondStepAttendGroup();
      }
    });
  };

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="CreateTask ThiftManagement">
        <div className="card-breadcrumb">
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/attendancemanagement/newattendanceunit">
                考勤组管理
              </Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>考勤方式</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div className="card">考勤方式</div>
        <div className="Steps">
          <Steps current={1}>
            <Step title="选择考勤类型" />
            <Step title="考勤地点" />
            <Step title="设置考勤人员" />
            <Step title="完成" />
          </Steps>
        </div>
        <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
          <FormItem
            className="addressRange-className"
            {...formItemLayout}
            label="设置出勤地点"
          >
            <Row span={24}>
              <Row>
                <Col span={10}>
                  <Button
                    type="primary"
                    ghost
                    onClick={() => {
                      this.setState({ visible: true });
                    }}
                  >
                    添加地点
                  </Button>
                  <span className="exclamation">
                    <Icon type="exclamation-circle" />可设置多个考勤地点
                  </span>
                </Col>
                <Col style={{ textAlign: "right" }} span={4}>
                  有效范围：
                </Col>
                <Col span={10}>
                  {getFieldDecorator("addressRange", {
                    initialValue: this.state.addressRange,
                    rules: [
                      { required: true, message: "请输入" },
                      {
                        validator: (rule, value, cb) => {
                          if (
                            !vd.isNumeric(value + "") ||
                            value <= 0 ||
                            (value + "").length > 10
                          ) {
                            cb("只能是正整数最长10位");
                          }

                          // Note: 必须总是返回一个 callback，否则 validateFieldsAndScroll 无法响应
                          cb();
                        }
                      }
                    ]
                  })(
                    <Input
                      onChange={e => {
                        this.setState({ addressRange: e.target.value });
                      }}
                      addonAfter="米"
                      placeholder="请输入"
                    />
                  )}
                </Col>
              </Row>
            </Row>
          </FormItem>
          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            <Table
              style={{ marginTop: 16 }}
              size="middle"
              pagination={false}
              columns={this.columns}
              dataSource={this.state.comAttendAddressJson}
            />
          </FormItem>

          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            <Button
              onClick={() => {
                this.props.history.replace(
                  `/attendancemanagement/selectionattendancetype?attendGroupId=${
                    this.state.attendGroupId
                  }&midAttendGroupId=${this.state.midAttendGroupId}`
                );
              }}
              loading={submitting}
            >
              返回
            </Button>
            <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit">
              确认并进行下一步
            </Button>
          </FormItem>
        </Form>

        <Modal
          title="添加地点"
          visible={this.state.visible}
          okText="提交"
          cancelText="关闭"
          onOk={() => {
            this.setState({ visible: false });
            let { comAttendAddressJson } = this.state;
            const { point, address } = this.state;
            comAttendAddressJson.push({
              address,
              addressLongitude: point[0],
              addressLatitude: point[1]
            });
            comAttendAddressJson = comAttendAddressJson.map((val, i) => {
              val.key = i;
              return val;
            });
            this.setState({ comAttendAddressJson });
          }}
          onCancel={() => {
            this.setState({ visible: false });
          }}
          width={700}
        >
          {
            <PMap
              areaChange={(point, address) => {
                console.log(point, address, "point,address");
                this.setState({ point, address });
              }}
              ifProvince={false}
            />
          }
        </Modal>
      </div>
    );
  }
}
